import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

import { Course } from '../interfaces/course.interface';
import { CourseService } from 'src/app/services/course/course.service';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'app-features',
  templateUrl: './features.component.html',
  styleUrls: ['./features.component.css']
})
export class FeaturesComponent implements OnInit {
  searchValue = '';
  @Input() listOfAllData: Course[];
  @Output() searched = new EventEmitter<Course[]>();
  @Input() mapOfCheckedId: { [key: string]: boolean } = {};
  takeSourseButtonDisabled = false;

  constructor(
    private courseService: CourseService,
    private message: NzMessageService
  ) {}

  ngOnInit() {}

  search(): void {
    this.searched.emit(
      this.listOfAllData.filter(course => {
        return course.name.indexOf(this.searchValue) !== -1;
      })
    );
  }

  takeCourses() {
    this.takeSourseButtonDisabled = true;

    // 生成选中的课程数组
    const selectedCourses = [];
    for (const key in this.mapOfCheckedId) {
      if (this.mapOfCheckedId.hasOwnProperty(key)) {
        const element = this.mapOfCheckedId[key];
        if (element) {
          selectedCourses.push(key);
        }
      }
    }

    if (0 === selectedCourses.length) {
      this.takeSourseButtonDisabled = false;
      return;
    }

    this.courseService.selectCourse(selectedCourses).subscribe(
      data => {
        if (data.cou_fail.length) {
          this.message.create('warning', '重复选课！');
        } else {
          this.message.create('success', '选课成功！');
        }

        this.takeSourseButtonDisabled = false;
      },
      error => {
        this.message.create('error', '选课失败！');
        this.takeSourseButtonDisabled = false;
      }
    );
  }
}
